package com.mf.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mf.entity.bo.RoleByUserBo;
import com.mf.mapper.PermissionByRoleMapper;
import com.mf.mapper.RoleByUserMapper;
import com.mf.mapper.RoleMapper;
import com.mf.service.IRoleService;
import io.github.heollhai.common.config.exceptions.GraceException;
import io.github.heollhai.common.entity.bo.RoleBo;
import io.github.heollhai.common.entity.request.publicRequest.PublicBindingIdRequest;
import io.github.heollhai.common.utils.VerifyUtils;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 角色表 服务实现类
 *
 * @author mf
 * @since 2024-08-06
 */
@Service
@Slf4j
public class RoleServiceImpl extends ServiceImpl<RoleMapper, RoleBo> implements IRoleService {
    @Resource
    private RoleMapper roleMapper;

    @Resource
    private PermissionByRoleMapper permissionByRoleMapper;

    @Resource
    private RoleByUserMapper roleByUserMapper;

    /**
     * 根据用户id查询绑定的角色id集合
     */
    @Override
    public List<Integer> findListByRoleId(Integer userId) {
        LambdaQueryWrapper<RoleByUserBo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RoleByUserBo::getUserId, userId);
        List<RoleByUserBo> roleByUserBos = roleByUserMapper.selectList(queryWrapper);
        return roleByUserBos.stream().map(RoleByUserBo::getRoleId).toList();
    }

    @Override
    @Transactional
    public Integer removeRoleById(Integer id) {
        // 根据角色id查询有无绑定用户
        List<String> User = roleMapper.findUserBindingRoleById(id);

        // 如果有绑定用户则抛出异常
        if (VerifyUtils.isNotEmpty(User)) {
            GraceException.display("该角色下有绑定用户"+ User + "无法删除");
        }

        // 删除角色权限表中的数据
        permissionByRoleMapper.deleteByRoleId(id);

        // 删除角色
        return roleMapper.deleteById(id);
    }

    @Override
    @Transactional
    public Boolean userBindingRole(PublicBindingIdRequest bindingIdRequest) {
        LambdaQueryWrapper<RoleByUserBo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RoleByUserBo::getUserId, bindingIdRequest.getTargetId());
        // 删除已绑定的角色
        roleByUserMapper.delete(queryWrapper);
        // 绑定新的角色
        return roleMapper.userBindingRole(bindingIdRequest);
    }
}
